/**
 * Created by tangqiaojie <2482366539@qq.com> on 2020/4/16 0016
 */
import { insertJQuery, nextTick, autoLoad } from '../../lib/utils.js';
import { asyncSetInterval, fixZeroInfo } from '../../lib/zeroReportUtils.js';

const clickItem = (item, time) => {
  setTimeout(() => {
    if (item.length) {
      item.click();
      setTimeout(() => {
        item.click();
      }, 200);
    }
  }, time);
};

let maskNone = function () {
  let maskFrmSheet = $('body > div[id="maskFrmSheet"]');
  return Array.from(maskFrmSheet).every(
    (item) => $(item).css('display') === 'none'
  );
};

let fsBlur = function(event, window) {
  var $this = event;
  if ($this.attr('type') == 'radio') { return; }
  let _jpath = $this.attr('jpath');
  // 2、执行关联公式计算
  let $parentDynamicScope = this.getParentDynamicScope(this);

  // var cIdx = this.$$childHead.$index;
  let dynamicIdx = null;
  if ($parentDynamicScope != null) {
    let pIdx = $parentDynamicScope.$index;
    dynamicIdx = [pIdx, this.$index];
    _jpath = _jpath.replace(/\[\d+\]/, '[99999_mh_]').replace(/\[\d+\]/, '[0]').replace('_mh_', '');
  } else if (typeof this.$index !== 'undefined') {
    dynamicIdx = [this.$index];
  }

  window.parent.formulaEngine.apply(_jpath, $this.val(), dynamicIdx);
  // 若有子级关联节点，则校验子级关联节点 Added By C.Q 20170704
  let affectNode = $this.attr('affectNode');
  if (affectNode) {
    window.viewEngine.applyAffNode(affectNode, _jpath); // 递归校验所有子级关联节点
  }
  // 3、刷新angular视图
  window.viewEngine.formApply($('#viewCtrlId'));
  // 4、刷新校验结果和控制结果
  // modify by lizhengtao 20160616 发现光校验$scope 下的$element还不够，
  // 比如下面单元格填写值涉及到上面单元格改变，此时需要连上面单元格一起校验
  window.viewEngine.tipsForVerify(document.body);// el
};

async function asyncQysdsTable (tabs, frmMain, frmtext) {
  let A201010 = tabs.find((item) => $(item).text().includes(frmtext));
  A201010.click();
  let frmSheetHref = $(A201010).attr('href');
  return asyncSetInterval(() => {
    let frmSheet = frmMain.find('#frmSheet');
    if (frmSheet.length
            && frmSheet.attr('src') === frmSheetHref
            && maskNone()) {
      return asyncSetInterval(() => {
        $('#btnSaved').click();
        return true;
      });
    }
  }).then(() => {
    return asyncSetInterval(() => {
      let content = $('.layui-layer-dialog .layui-layer-content');
      if (content.length) {
        if (content.text().includes('保存成功')) {
          $('.layui-layer-dialog .layui-layer-btn0').click();
        } else {
          window.location.reload();
        }
        return true;
      }
    });
  });
}

const incomeReport = ({
  quarterSum, endSum, corporationName, corporationIdcard, endPeriod, recordList
}) => {
  let tabs = null;
  let frmMain = null;
  return asyncSetInterval(() => {
    frmMain = $('#frmMain');
    if (frmMain.length) {
      frmMain = frmMain.contents();
      return true;
    }
  }, 1000)
    .then(() => {
      return asyncSetInterval(() => {
        let divSheetlist = frmMain.find('#divSheetlist > li > a');
        if (divSheetlist.length) {
          tabs = Array.from(divSheetlist);
          return true;
        }
      }, 2000);
    })
    .then(() => {
      // A200000
      let A200000 = tabs.find((item) =>
        $(item).text().includes('A200000中华人民共和国企业所得税月'));
      let frmSheetHref = $(A200000).attr('href');
      A200000.click();
      if (frmMain.find('.layui-layer-btn0').length) {
        frmMain.find('.layui-layer-btn0')[0].click();
      }
      return asyncSetInterval(() => {
        let frmSheet = frmMain.find('#frmSheet');
        let jds = {
          3: 1,
          6: 2,
          9: 3,
          12: 4
        };
        if (
          frmSheet.length
          && frmSheet.attr('src') === frmSheetHref
          && maskNone()
        ) {
          let win = frmSheet[0].contentWindow;
          let angular = win.angular;
          let controllerScope = angular.element('#viewCtrlId').scope();
          let jd = jds[endPeriod];
          let whiteArr = [`qccyrs${jd}`, `qmcyrs${jd}`, `qczcze${jd}`, `qmzcze${jd}`, 'gjxzhjzhy', 'sfgxjsqy', 'sfkjxzxqy', 'sffsjsrgdynssx'];
          let whireArr1 = ['nsrqtxxForm.jbr', 'nsrqtxxForm.jbrzyzjhm'];
          controllerScope.sbbxxForm[whiteArr[0]] = controllerScope.sbbxxForm[whiteArr[0]] || 1;
          controllerScope.sbbxxForm[whiteArr[1]] = controllerScope.sbbxxForm[whiteArr[1]] || 1;
          controllerScope.sbbxxForm[whiteArr[2]] = parseFloat(quarterSum) || controllerScope.sbbxxForm[whiteArr[2]] || 0.01;
          controllerScope.sbbxxForm[whiteArr[3]] = parseFloat(endSum) || controllerScope.sbbxxForm[whiteArr[3]] || 0.01;
          controllerScope.sbbxxForm.gjxzhjzhy = 'N';
          controllerScope.sbbxxForm.sfgxjsqy = 'N';
          controllerScope.sbbxxForm.sfkjxzxqy = 'N';
          controllerScope.sbbxxForm.sffsjsrgdynssx = 'N';
          controllerScope.nsrqtxxForm.jbr = corporationName;
          controllerScope.nsrqtxxForm.jbrzyzjhm = corporationIdcard;
          angular.element('#viewCtrlId').scope().$apply();
          whiteArr.forEach(item => {
            let ele = win.document.querySelector(`input[ng-model="sbbxxForm.${item}"]`);
            win.parent.formulaEngine.apply($(ele).attr('jpath'), $(ele).val(), null);
          });
          whireArr1.forEach(item => {
            let ele = win.document.querySelector(`input[ng-model="${item}"]`);
            win.parent.formulaEngine.apply($(ele).attr('jpath'), $(ele).val(), null);
          });
          win.viewEngine.formApply('#viewCtrlId');
          win.viewEngine.tipsForVerify(document.body);
          return true;
        }
      }, 1000).then(() => {
        return asyncSetInterval(() => {
          $('#btnSaved').click();
          return true;
        });
      }).then(() => {
        return asyncSetInterval(() => {
          let content = $('.layui-layer-dialog .layui-layer-content');
          if (content.length) {
            if (content.text().includes('保存成功')) {
              $('.layui-layer-dialog .layui-layer-btn0').click();
            } else {
              window.location.reload();
            }
            return true;
          }
        });
      });
    }).then(() => {
      return asyncQysdsTable(tabs, frmMain, 'A201010免税收入');
    })
    .then(() => {
      return asyncQysdsTable(tabs, frmMain, 'A201020资产加速折旧');
    })
    .then(() => {
      return asyncQysdsTable(tabs, frmMain, 'A201030减免所得税优惠明细表');
    })
    .then(() => {
      return asyncQysdsTable(tabs, frmMain, '居民企业参股外国企业信息报告表');
    })
    .then(() => {
      $('#btnPrepareMake').click();
      return asyncSetInterval(() => {
        let content = frmMain.find('.layui-layer-dialog .layui-layer-content');
        if (content.length) {
          if (content.text().includes('您确定要提交申报吗')) {
            // layui-layer-btn0
            frmMain.find('.layui-layer-dialog .layui-layer-btn0')[0].click();
            return true;
          }
          window.location.reload();
        }
      }).then(() => {
        return asyncSetInterval(() => {
          let content = $('.layui-layer-dialog .layui-layer-content');
          if (content.length) {
            if (content.text().includes('为了给您提供更佳的办税体验')) {
              $('.layui-layer-dialog .layui-layer-btn0').click();
            } else {
              window.location.reload();
            }
            return true;
          }
        });
      });
    })
    .then(() => {
      return asyncSetInterval(() =>{
        frmMain = $('#frmMain');
        if (frmMain.length && frmMain.contents().find('body > div > h3').length) {
          if (frmMain.contents().find('body > div > h3').text().includes('申报成功')) {
            // currentToTaxindex({});
            let qysds = recordList.find(item => item.declareName.includes('企业所得税(月季报'));
            qysds.isSuccess = true;
            fixZeroInfo({ recordList: [qysds] });
            setTimeout(() => {
              window.location.href = '/xxmh/html/index_login.html';
            }, 1000);
          }
        }
      }, 3000);
    })
    .catch(() => {
      window.location.reload();
    });
};

export { incomeReport };
